package cn.xmkeshe.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

/**
 * shiro配置类
 * 
 * @author
 *
 */
@Configuration
public class ShiroConfig {
	
	// thymeleaf与Shiro集成
	@Bean
	public ShiroDialect shiroDialect() {
		return new ShiroDialect();
	}

	// 创建ShiroFilterFactoryBean
	@Bean(name = "shiroFilterFactoryBean")
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(
			@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		// 设置安全管理器
		shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
		Map<String, String> shiroFilter = new HashMap<String, String>();
		// 拦截页面
//		shiroFilter.put("/pages/front/**", "authc");
		shiroFilter.put("/pages/back/**", "authc");
		// 被拦截返回登录页面
		shiroFilterFactoryBean.setLoginUrl("/loginPre");
		// 授权拦截返回页面
		shiroFilterFactoryBean.setUnauthorizedUrl("/loginPre");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroFilter);
		return shiroFilterFactoryBean;

	}

	@Bean(name = "defaultWebSecurityManager")
	public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("adminRealm") AdminRealm adminRealm) {
		DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
		defaultWebSecurityManager.setRealm(adminRealm);
		return defaultWebSecurityManager;
	}

	// 创建Realm
	@Bean(name = "adminRealm")
	public AdminRealm getAdminRealm() {
		return new AdminRealm();
	}

}